from orange.planner.models import Department
from orange.planner.models import Course
from django.core.management.base import BaseCommand, CommandError
import csv

class Command(BaseCommand):
  args = '<majors.csv classes.csv>'
  help = 'Imports a list of classes and majors'

  def handle(self, *args, **options):
    if len(args) != 2:
      print args
      raise CommandError('Wrong number of arguements')
    majors_csv = csv.reader(open(args[0]))
    classes_csv = csv.reader(open(args[1]))
    print 'load successful'
    # Majors
    majors_csv.next()  # Read first line, its a header line
    classes_csv.next()  # Header
    for key, long_name, short_name in majors_csv:
      print key, long_name, short_name
      if Department.objects.filter(short_name=short_name): continue
      d = Department(short_name=short_name, long_name=long_name)
      d.save()
    # Courses
    for row in classes_csv:
      print row
      if not row: continue
      key, long_name, major, short_name = row
      print major, short_name, long_name
      d = Department.objects.get(short_name=major)
      if Course.objects.filter(short_name=key): continue
      c = Course(dept=d, number=short_name, long_name=long_name, short_name=key)
      c.save()